package com.lhh.userservice.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lhh.springcommon.annotation.WebLog;
import com.lhh.springcommon.entity.Chat;
import com.lhh.springcommon.entity.User;
import com.lhh.springcommon.entity.vo.ChatVO;
import com.lhh.springcommon.service.IChatService;
import com.lhh.springcommon.service.IUserService;
import com.lhh.springcommon.utils.PageQuery;
import com.lhh.springcommon.interceptor.JwtInterceptor;
import com.lhh.userservice.service.UserChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 李厚航
 * @date 2025-03-01 22:02
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UserChatServiceImpl implements UserChatService {

    private final IChatService chatService;

    private final IUserService userService;

    @Autowired
    public UserChatServiceImpl(IChatService chatService, IUserService userService) {
        this.chatService = chatService;
        this.userService = userService;
    }

    @Override
    @WebLog
    @Cacheable(value = "chatUnreadCount",key = "T(com.lhh.springcommon.interceptor.JwtInterceptor).userIdFromThreadLocal")
    public Integer countUnread() {
        Integer fid = JwtInterceptor.getUserIdFromThreadLocal();
        //查询fid=fid且unread=0的条数
        return (int)chatService.count(new LambdaQueryWrapper<Chat>().eq(Chat::getFid, fid).eq(Chat::getUnread, 0));
    }

    @Override
    @WebLog
    @CacheEvict(value = "chatPage", allEntries = true)
    public Chat add(Chat chat) {
        //添加一条数据
        chatService.save(chat);
        return chat;
    }

    @Override
    @WebLog
    @Cacheable(value = "chatPage",key = "#chat.page + ':' + #chat.pageSize + ':' + #chat.queryInfo.uid + ':' + #chat.queryInfo.fid")
    public Page<Chat> queryPageChat(PageQuery<Chat> chat) {
        Page<Chat> page = new Page<>(chat.getPage(), chat.getPageSize());
        Chat queryInfo = chat.getQueryInfo();
        return chatService.page(page,new LambdaQueryWrapper<Chat>()
                .eq(queryInfo.getId()!=null, Chat::getId, queryInfo.getId())
                .eq(queryInfo.getUid()!=null, Chat::getUid, queryInfo.getUid())
                .eq(queryInfo.getFid()!=null, Chat::getFid, queryInfo.getFid())
                .eq(queryInfo.getMessage()!=null, Chat::getMessage, queryInfo.getMessage())
                .eq(queryInfo.getCreateTime()!=null, Chat::getCreateTime, queryInfo.getCreateTime())
                .eq(queryInfo.getUnread()!=null, Chat::getUnread, queryInfo.getUnread()).orderByAsc(Chat::getCreateTime));
    }

    @Override
    @WebLog
    @CacheEvict(value = "chatUnreadCount",key = "T(com.lhh.springcommon.interceptor.JwtInterceptor).userIdFromThreadLocal")
    public String checkChat() {
        Integer fid = JwtInterceptor.getUserIdFromThreadLocal();
        //将unread=0的置为1
        chatService.update(new LambdaUpdateWrapper<Chat>()
                .eq(Chat::getFid, fid)
                .eq(Chat::getUnread, 0)
                .set(Chat::getUnread, 1));
        return null;
    }

    @Override
    @WebLog
    @Cacheable(value = "chatPage",key = "#fid")
    public List<ChatVO> queryByFid(Integer fid) {
        List<Chat> chats = chatService.list(new LambdaQueryWrapper<Chat>().eq(Chat::getFid, fid));
        if(chats.isEmpty()){
            return null;
        }
        List<Integer> id = new ArrayList<>();
        for (Chat c:chats) {
            id.add(c.getUid());
        }
        List<User> users = userService.list(new LambdaQueryWrapper<User>().in(User::getId, id));
        return users.stream().map(u ->
                new ChatVO(u.getId(),u.getName(),u.getAvatarUrl(),chats.stream().filter(chat -> chat.getUid().equals(u.getId())).collect(Collectors.toList()))
        ).collect(Collectors.toList());
    }
}
